#!/bin/sh

source "{{ m_install }}/.deploy-meza/config.sh"

if [ -z "$1" ]; then
	do_wikis="*/"
else
	do_wikis="$1"
fi

wiki_dir="{{ m_htdocs }}/wikis"

cd "$wiki_dir"
for d in $do_wikis; do

	if [ -z "$1" ]; then
		wiki_id=${d%/}
	else
		wiki_id="$d"
	fi

	if [ ! -d "$wiki_dir/$wiki_id" ]; then
		echo "\"$wiki_id\" not a valid wiki ID"
		continue
	fi

	timestamp=$(date +"%F_%T")
	out_log="{{ m_logs }}/refresh-links/$wiki_id.$timestamp.log"

	echo "Start refreshing links for \"$wiki_id\" at $timestamp"
	echo "  Output log:"
	echo "    $out_log"

	num_pages=$(WIKI="$wiki_id" php "{{ m_mediawiki }}/maintenance/showSiteStats.php" | grep "Total pages" | sed 's/[^0-9]*//g')
	end_id=0
	delta=2000

	echo "Beginning refreshLinks.php script for $wiki_id"
	echo "  Total pages = $num_pages"
	echo "  Doing it in $delta-page chunks to avoid memory leak"

	while [ "$end_id" -lt "$num_pages" ]; do
		start_id=$(($end_id + 1))
		end_id=$(($end_id + $delta))
		echo "Running refreshLinks.php from $start_id to $end_id for $wiki_id"
		WIKI="$wiki_id" php "{{ m_mediawiki }}/maintenance/refreshLinks.php" --e "$end_id" -- "$start_id" >> "$out_log" 2>&1

		# If the above command had a failing exit code
		if [[ $? -ne 0 ]]; then
			endtimestamp=$(date +"%F_%T")

			# FIXME #577 #681: add notification/warning system here
			echo "refreshLinks FAILED for \"$wiki_id\" at $endtimestamp"
		fi

	done

	# Just in case there are more IDs beyond the guess we made with showSiteStats, run
	# one more unbounded refreshLinks.php starting at the last ID previously done
	start_id=$(($end_id + 1))
	echo "Running final refreshLinks.php for $wiki_id in case there are more pages beyond $num_pages"
	WIKI="$wiki_id" php "{{ m_mediawiki }}/maintenance/refreshLinks.php" "$start_id" >> "$out_log" 2>&1

	# If the above command had a failing exit code
	if [[ $? -ne 0 ]]; then
		endtimestamp=$(date +"%F_%T")

		# FIXME #577 #681: add notification/warning system here
		echo "refreshLinks FAILED for \"$wiki_id\" at $endtimestamp"

	#if the above command had a passing exit code (e.g. zero)
	else
		endtimestamp=$(date +"%F_%T")
		echo "refreshLinks completed for \"$wiki_id\" at $endtimestamp"
	fi

done
